package com.gdteam.kernel.content;

import java.io.File;

import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;

/**
 * Utility class used to provide Document from File
 * @author erwan
 *
 */
public class FileDocument {
    
    private FileDocument() {
    }

    public static Document document(File f)  {
        try {
            Document doc = new Document();
        
            // Add the path of the file as a field named "path".  Use a field that is 
            // indexed (i.e. searchable), but don't tokenize the field into words.
            doc.add(new Field("path", f.getPath(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            
            // Adding file title
            doc.add(new Field("title", f.getName(),Field.Store.YES, Field.Index.NOT_ANALYZED));
        
            // Adding file extension, if exists
            int idx = f.getName().lastIndexOf(".");
            if (-1 != idx) {
                String ext = f.getName().substring(idx+1);
                doc.add(new Field("extension",ext,Field.Store.YES, Field.Index.NOT_ANALYZED));
            } 
            
            // Add the last modified date of the file a field named "modified".  Use 
            // a field that is indexed (i.e. searchable), but don't tokenize the field
            // into words.
            doc.add(new Field("modified", DateTools.timeToString(f.lastModified(), DateTools.Resolution.MINUTE),
                Field.Store.YES, Field.Index.NOT_ANALYZED));
        
            // Add the contents of the file to a field named "contents".  Specify a Reader,
            // so that the text of the file is tokenized and indexed, but not stored.
            // Note that FileReader expects the file to be in the system's default encoding.
            // If that's not the case searching for special characters will fail.
            //doc.add(new Field("contents", new FileReader(f)));
        
            // return the document
            return doc;
            
        } catch(Exception ioe) {
            return null;
        }
    }
}
